package com.sunyur.tailor.channel.web.outer.expense.controller;

import com.alibaba.fastjson.JSON;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.expense.param.ExpenseTypeListParam;
import com.sunyur.tailor.channel.service.inner.expense.param.ExpenseTypeStatusListParam;
import com.sunyur.tailor.channel.service.inner.expense.service.SunyurExpenseTypeService;
import com.sunyur.tailor.channel.web.outer.expense.dto.ExpenseTypeListDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @Description 费用类型
 * @Date 14:02 2021/12/29
 * @Param
 * @return
**/
@Slf4j
@RestController
@RequestMapping("/outer/expenseType")
public class ExpenseTypeController {

    /**
     * 费用类型服务
     */
    @Autowired
    private SunyurExpenseTypeService sunyurExpenseService;

    /**
     * 批量创建费用类型
     */
    @PostMapping(value = "/batchSyncExpenseType", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChannelResult<Boolean> batchSyncExpenseType(@RequestBody @Valid ExpenseTypeListDTO expenseTypeListDTO) {
        log.info("ExpenseController batchSyncExpenseType param:{}", JSON.toJSONString(expenseTypeListDTO));
        ChannelResult<Boolean> result = new ChannelResult<>();
        try {
            //批量修改费用类型
            ExpenseTypeListParam expenseTypeListParam = new ExpenseTypeListParam();
            BeanUtils.copyProperties(expenseTypeListDTO, expenseTypeListParam);
            result = sunyurExpenseService.batchSyncExpenseType(expenseTypeListParam);
            if(ChannelResultUtil.isSuccess(result)){
                //批量修改费用类型的状态
                ExpenseTypeStatusListParam expenseTypeStatusListParam = new ExpenseTypeStatusListParam();
                List<String> expenseTypeCodes = expenseTypeListDTO.getExpenseTypes().stream().map(ExpenseTypeListDTO.ExpenseTypeDTO::getOutSideCode).collect(Collectors.toList());
                expenseTypeStatusListParam.setExpenseTypeCodes(expenseTypeCodes);
                expenseTypeStatusListParam.setModifyCode(1);
                result = sunyurExpenseService.batchSyncExpenseTypeStatus(expenseTypeStatusListParam);
            }
        } catch (Exception e) {
            log.error("ExpenseController batchSyncExpenseType exception:{}", e);
            result.setError(MiddleResultEnum.EXCEPTION.getCode(), MiddleResultEnum.EXCEPTION.getValue());
        }
        log.info("ExpenseController batchSyncExpenseType return:{}", JSON.toJSONString(result));
        return result;
    }
}
